import { onBeforeUnmount, onMounted } from "vue";


export function useAutoLoader(loader, timeInterval = 60000) {
    let latestLoadTime = new Date()
    function loadIfNeeds(loader) {
        if (latestLoadTime.getTime() < (new Date()).getTime()) {
            loader()
            latestLoadTime = new Date()
        }
    }
    let timer = undefined
    onMounted(() => {
        console.log('onMounted')
        loader()
        timer = window.setInterval(() => loadIfNeeds(loader), timeInterval)
    })
    onBeforeUnmount(() => {
        console.log('onBeforeUnmount')
        window.clearInterval(timer)
    })

    return () => {
        console.log('cancel')
        window.setInterval(timer)
    }
}